"""Django view classes for a simple Blog site

   This example shows several simple views that retrieve
   the appropriate objects, populate a template context
   and then render the template.
"""

from django.shortcuts import render_to_response, get_object_or_404
from simpleblog.dblog.models import Blog
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
import django.views.generic.simple
from django.http import HttpResponse

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.core import serializers

from datetime import datetime
import time


@login_required
def addComment(*args, **kwargs):
    return django.views.generic.list_detail.object_detail(*args, **kwargs)

@login_required
def addEntry(request, *args, **kwargs):
    if not (request.user.has_perm("dblog.may_create_blogs")):
      return HttpResponse("Permission Denied")
    else:
      return django.views.generic.simple.direct_to_template(request, *args, **kwargs)

def getComments(request, blog_id):
  b = get_object_or_404(Blog, pk=blog_id)
  jsontext = serializers.serialize("json", b.comment_set.all())
  time.sleep(2)
  return HttpResponse(jsontext, "application/json")

def newUser(request):
  """Creates a new user with comment-only permissions"""
  if request.POST:
    try:
      username = request.POST['username']
      password = request.POST['password']
      email = request.POST['email']
      firstname = request.POST['firstname']
      lastname = request.POST['lastname']
      if (len(username) == 0 or
          len(password) == 0 or
          len(email) == 0 or
          len(firstname) == 0 or
          len(lastname) == 0):
        return render_to_response('dblog/newUser.html', 
            {'username':username,
             'email':email, 
             'firstname':firstname,
             'lastname':lastname,
             'msg':'All fields are required. Please resubmit.'})
      user = User.objects.create_user(username, email, password)
      user.first_name = firstname
      user.last_name = lastname
      user.save()
      # Log the user in here
      # This should be successful because we just created the user 
      # with that password
      newuser = authenticate(username=username, password=password)
      login(request, newuser)
      return HttpResponseRedirect('/accounts/profile/')
    except:
      import sys,traceback
      traceback.print_exc()
      print sys.exc_info()
        
      # If the username is already in use, a constraint error is thrown.
      # The type of exception thrown depends on the database backend in use
      # so here we assume that any exception is a 
      # "username already in use" error
      return render_to_response('dblog/newUser.html', 
          {'email':email, 
           'firstname':firstname,
           'lastname':lastname,
           'msg':'Username "%s" is in use. Please choose another.'%
           username})
#    else:
  return render_to_response('dblog/newUser.html', {})


@login_required
def postEntry(request):
    """Accepts the HTTP POST data of a new blog entry and 
       updates the database accordingly"""
    if not (request.user.has_perm("dblog.may_create_blogs")):
      return HttpResponse("Permission Denied")
    b = Blog()
    b.title = request.POST['title']
    b.reply_to = request.POST['reply_to']
    b.content = request.POST['content']
    b.post_date = datetime.now()
    b.save()
    return HttpResponseRedirect('/simpleblog/blog/%s/' % b.id)

@login_required
def postComment(request, blog_id):
    """Accepts the HTTP POST data of a new blog comment and updates
       the database accordingly"""
    blog = get_object_or_404(Blog, pk=blog_id)
    comment = blog.comment_set.create(content=request.POST['content'], 
                                      rating=request.POST['rating'])
    comment.save()
    return HttpResponseRedirect('/simpleblog/blog/%s/comment' % blog.id)

def viewProfile(request):
    return render_to_response('dblog/user_profile.html', {}, RequestContext(request))
